from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from . import spu_serializers
from goods.models import SPU, Brand, GoodsCategory
from meiduo_mall_admin.my_paginate import MyPageNumberPagination
from rest_framework.generics import ListAPIView


# 获取spu的数据表
class SPUViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = spu_serializers.SPUViewSetSerializer
    queryset = SPU.objects.all()


# 获取品牌名称信息
class SPUSimpleVIews(ListAPIView):
    serializer_class = spu_serializers.SPUSimpleSerializer
    queryset = Brand.objects.all()


# 获取一级分类商品
class SPUCategoriesVIews(ListAPIView):
    serializer_class = spu_serializers.SPUCategoriesSerializer
    queryset = GoodsCategory.objects.filter(parent_id=None).all()


# 二三级分类
class SPUCategorySubView(ListAPIView):
    serializer_class = spu_serializers.SPUCategoriesSerializer
    def get_queryset(self):
        category_id = self.kwargs.get("category_id")

        # 当前级要一个,所以用get,当前级的下一级有很多个,所有点all()
        return GoodsCategory.objects.get(id=category_id).subs.all()


# 图片上传
class SPUImagesView(APIView):
    def post(self, request):
        # 获取图片
        image = request.FILES.get("image")
        # 校验图片
        if not image:
            return Response(status=400)

        # 图片入库
        client = Fdfs_client(settings.FDFS_CONFIG)   # 配置好客户端
        ret = client.upload_by_buffer(image.read())

        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 4,返回响应, 并拼接好路径
        return Response({
            "img_url": settings.BASE_URL + ret.get("Remote file_id")
        })




